package com.manager;

import world.World;

import com.game.activity.MainActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.manager.MessageType;
import com.manager.ReturnState;

public class ViewManager implements Runnable {
	public static final String TAG = "ViewManager";
	
	private UIHandler UIHandler;
	private boolean running;
	
	public ViewManager() {
		UIHandler = MainActivity.UIHandler;
		this.running = true;
	}

	@Override
	public void run() {
		while (QuestMainService.gm == null) {
			try {
				Thread.currentThread().sleep(10);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		if (QuestMainService.gm.getCharGenState() == ReturnState.NEW_SERVICE) {
			log("ViewManager is waiting.");
			synchronized(MainActivity.managerSynchLock) {
				try {
					MainActivity.managerSynchLock.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			log("ViewManager is continuing.");
			
			ReturnState charGenState = QuestMainService.gm.getCharGenState();
			
			Message msg = UIHandler.obtainMessage();
			Bundle bundle = new Bundle();
			if (charGenState == ReturnState.PLAYER_EXISTS) {
				log("Player does exist - initializing view.");
				bundle.putSerializable("msg", MessageType.MESSAGE_INIT_MAIN);
			} else if (charGenState == ReturnState.PLAYER_DOES_NOT_EXIST) { 
				log("Player does not exist - starting character creation.");
				bundle.putSerializable("msg", MessageType.MESSAGE_INIT_CREATION);
				synchronized(MainActivity.managerSynchLock) {
					synchronized(MainActivity.UISynchLock) {
						try {
							MainActivity.UISynchLock.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}
			msg.setData(bundle);
			UIHandler.sendMessage(msg);
					
			synchronized(MainActivity.managerSynchLock){
				if(QuestMainService.gameLoopThread.getState() == Thread.State.WAITING){
					/* gameLoopThread finished waiting */
					MainActivity.managerSynchLock.notify();
					log("ViewManager woke GameLoop.");
				} else {
					try {
						log("ViewManager waiting.");
						MainActivity.managerSynchLock.wait();
						log("ViewManager started again.");
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		} else {
			Message msg = UIHandler.obtainMessage();
			Bundle bundle = new Bundle();
			bundle.putSerializable("msg", MessageType.MESSAGE_INIT_MAIN);
			msg.setData(bundle);
			UIHandler.sendMessage(msg);
		}
	}
	
	public void log(String message) {
		Log.d(ViewManager.TAG, message);
	}
}